#!/usr/bin/python
# -*- coding: utf-8 -*-

u"""
"""

__version__ = '$Id: todo.py 166 2008-08-28 18:55:36Z DR0ID $'


import os
import glob
import re
import datetime

#                low                                    heigh
TASK_CHOICES = ['ALL', 'NOTE', 'TODO', 'HACK', 'XXX', 'FIXME']

RE_TASK_CHOICES = []
for task in TASK_CHOICES:
    expr = r"""(?i)#\s*""" + task + r"""\s*:(.*$)"""
    RE_TASK_CHOICES.append(re.compile(expr, re.UNICODE))



def _get_filenames(root_dir):
    src_files = []
    for p, dirs, files in os.walk(root_dir):
        names = glob.glob(os.path.join(p, '*.py'))
        src_files.extend(names)
        count = 0
        for idx, dir in enumerate(list(dirs)):
            if dir.startswith('.'):
                del dirs[idx - count]
                count += 1
            if dir == 'extern':
                del dirs[idx - count]
                count += 1
    return src_files



def scan(file_names):
    # TODO: check for missing doc strings and add a task
    tasks = []
    for name in file_names:
        print 'processing %s' % name
        try:
            fn = open(name, 'rb')
            lines = fn.readlines()
            for line_num, line in enumerate(lines):
                for prio, cre in enumerate(RE_TASK_CHOICES):
                    hit = cre.search(line)
                    if hit:
                        descr = hit.group(1).strip()
                        tasks.append((prio+descr.count('!'), TASK_CHOICES[prio], name, line_num, line.strip()))
        finally:
            fn.close()
    tasks.sort(lambda a, b: cmp(b[0], a[0]))
    
    target = 'TODO.txt'
    persis_bond = '###'+'-'*12+' end persistent section, DO NOT REMOVE THIS LINE '+'-'*15+'#\r\n\r\n'
    persistent = []
    if os.path.exists(target):
        todo = open(target, 'rb')
        try:
            # persistent section
            line = todo.readline()
            while not line.startswith('###--') and line != '':
                persistent.append(line)
                line = todo.readline()
            persistent.append(persis_bond)
        finally:
            todo.close()
    else:
        persistent.append('\r\n\r\n')
        persistent.append(persis_bond)

    try:
        # new parts
        todo = open(target, 'wb')
        todo.writelines(persistent)
        todo.write('last generated at: %s\r\n\r\n' % datetime.datetime.today())
        todo.write('possible tags (low to heigh priority): ALL, NOTE, TODO, HACK, XXX, FIXME\r\n\r\n')
        todo.write('prio \ttype \t file(line)\t\t\t description \r\n')
        todo.write('-'*80+'\r\n')
        maxw = 0
        for task in tasks:
            prio, ttype, name, line_nr, descr = task
            name = '%s (%d)' % (name, line_nr)
            if maxw < len(name):
                maxw = len(name)
            name = name.ljust(maxw)
            #print task
            todo.write('%d \t%s\t%s     %s\r\n' % (prio, ttype, name, descr))
    finally:
        todo.close()

    

# TODO: maybe add some comandline options
def main():
    root_dir = '.' #os.path.abspath(os.path.dirname(__file__))
    file_names = _get_filenames(root_dir)
    scan(file_names)



if __name__ == '__main__':
    main()


